package com.videoanalysis;

import com.videoanalysis.config.AppConfig;
import com.videoanalysis.recognizer.ImageRecognizer;
import com.videoanalysis.recognizer.ImageRecognizerFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 视频分析器主类，负责协调整个视频分析流程
 */
@Slf4j
public class VideoAnalyzer {
    private final FrameExtractor frameExtractor;
    private final ImageRecognizer imageRecognizer;
    private final AppConfig.OutputConfig outputConfig;
    private final AppConfig.FFmpegConfig ffmpegConfig;

    public VideoAnalyzer() {
        AppConfig config = AppConfig.getInstance();
        this.frameExtractor = new FrameExtractor(config.getFfmpeg().getPath());
        this.imageRecognizer = ImageRecognizerFactory.createImageRecognizer();
        this.outputConfig = config.getOutput();
        this.ffmpegConfig = config.getFfmpeg();
    }

    /**
     * 分析视频文件
     * @param videoFile 视频文件
     * @return 分析结果对象
     */
    public AnalysisResult analyzeVideo(File videoFile) {
        try {
            // 创建分析结果目录
            String resultDirPath = createResultDirectory(videoFile.getName());
            Path resultDir = Paths.get(resultDirPath);

            log.info("开始分析视频: {}", videoFile.getName());
            log.info("分析结果将保存在: {}", resultDir);

            // 复制原始视频到结果目录
            Path videoFileCopy = resultDir.resolve(videoFile.getName());
            Files.copy(videoFile.toPath(), videoFileCopy);

            // 创建帧提取目录
            Path framesDir = resultDir.resolve("frames");
            Files.createDirectories(framesDir);

            // 按时间间隔提取视频帧
            log.info("正在提取视频帧，间隔{}秒...", ffmpegConfig.getFrameIntervalSeconds());
            List<Path> extractedFrames = frameExtractor.extractFrames(videoFile, framesDir, ffmpegConfig.getFrameIntervalSeconds());
            log.info("提取了 {} 帧", extractedFrames.size());

            // 分析每一帧
            log.info("开始分析图像内容...");
            Map<Path, List<RecognitionResult>> recognitionResults = imageRecognizer.recognizeImages(extractedFrames);

            // 创建分析结果文件
            Path analysisFile = resultDir.resolve("analysis.json");
            AnalysisResult result = new AnalysisResult(
                    videoFile.getName(),
                    resultDir.toString(),
                    extractedFrames.size(),
                    recognitionResults,
                    LocalDateTime.now()
            );
            result.saveToFile(analysisFile);

            log.info("视频分析完成，结果已保存到: {}", analysisFile);
            return result;

        } catch (IOException e) {
            log.error("视频分析过程中发生错误", e);
            throw new RuntimeException("视频分析失败", e);
        }
    }

    /**
     * 创建用于存储分析结果的目录
     * @param videoFileName 视频文件名
     * @return 创建的目录路径
     * @throws IOException 如果目录创建失败
     */
    private String createResultDirectory(String videoFileName) throws IOException {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String baseName = videoFileName.replaceFirst("[.][^.]+$", ""); // 移除文件扩展名
        String dirName = "analysis_" + baseName + "_" + timestamp;

        // 使用配置的输出目录
        Path resultDir = Paths.get(outputConfig.getDirectory(), dirName);
        Files.createDirectories(resultDir);
        return resultDir.toString();
    }
}
